<template>
  <el-dialog v-if="load" :close-on-click-modal="false" title="申请退款" v-model="visible" align-center width="1300px" :z-index="2000" @close="handleClose">
    <el-form ref="formRef" :model="form" label-width="110px">
      <div class="v-title mb-3">基础信息</div>
      <div class="grid grid-cols-4 gap-x-3">
        <el-form-item label="供应商">
          <el-input v-model="form.basic.supplier_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="供应商类型">
          <VSelect v-model="form.basic.purchase_type" placeholder="请选择" :options="options.purchase_type || []" filterable clearable disabled />
        </el-form-item>
        <el-form-item label="结算方式">
          <el-input v-model="form.basic.period_name" placeholder="请输入" disabled />
        </el-form-item>
        <el-form-item label="公司主体">
          <VSelect v-model="form.basic.company_id" placeholder="请选择" :options="options.company_id || []" filterable clearable disabled />
        </el-form-item>
        <el-form-item label="退款类型">
          <VSelect v-model="form.basic.refund_type" placeholder="请选择" :options="(options.refund_type || []).filter(d => [4, 5].includes(d.value))" filterable clearable
            @change="refundTypeChange" />
        </el-form-item>
        <el-form-item label="收款方式" prop="basic.refund_method" :rules="[{ required: true, message: '不能为空', trigger: 'change' }]">
          <VSelect v-model="form.basic.refund_method" placeholder="请选择" :options="options.refund_method || []" filterable clearable />
        </el-form-item>
        <el-form-item label="收款账号">
          <el-input v-model="form.basic.refund_account" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="退款币种">
          <VSelect v-model="form.basic.refund_currency" placeholder="请选择" :options="options.currency || []" filterable clearable disabled />
        </el-form-item>
        <el-form-item label="退款交易号">
          <el-input v-model="form.basic.refund_transaction_no" placeholder="请输入" class="w-full" />
        </el-form-item>
        <el-form-item label="申请退款总金额">
          <el-input-number v-model="apply_refund_total" :controls="false" placeholder="请输入" precision="2" class="w-full"></el-input-number>
        </el-form-item>
        <el-form-item label="备注" class="col-span-full">
          <el-input v-model="form.basic.remark" placeholder="请输入" type="textarea" :autosize="{ minRows: 2, maxRows: 5 }" />
        </el-form-item>
        <el-form-item label="退款凭证" class="col-span-full">
          <VUpload v-model="form.basic.refund_voucher" :types="['jpg', 'jpeg', 'png', 'pdf','xls','xlsx']"/>
        </el-form-item>
      </div>
      <div class="v-title mb-3 mt-2 flex">
        <div class="flex-1">采购单信息</div>
        <div>
          <VText title="申请退款总金额" :value="apply_refund_total" class="ml-auto" />
        </div>
      </div>
      <vxe-table ref="tableRef" :data="form.purchase" size="small">
        <vxe-column title="采购单号" :min-width="140">
          <template #default="{ row }">
            <VText :value="row.purchase_no" />
          </template>
        </vxe-column>
        <vxe-column title="sku" field="sku" :min-width="100">
          <template #default="{ row }">
            <VText :value="row.sku" />
          </template>
        </vxe-column>
        <vxe-column title="下单金额" field="unit_price" :min-width="100">
          <template #default="{ row }">
            <div><span class='text-gray-500'></span>{{ row.is_drawback === 2 ?
              row.total_purchase_price_tax :
              row.total_purchase_price }}</div>
          </template>
        </vxe-column>
        <vxe-column title="运费" field="tracking_price" :min-width="80" />
        <vxe-column title="优惠" field="discount_price" :min-width="80" />
        <vxe-column title="已退款金额" field="refund_price" :min-width="80" />
        <vxe-column title="可退金额" field="can_refund_price" :min-width="80" />
        <vxe-column title="入库金额" field="inbound_price" :min-width="80" />
        <vxe-column title="已付金额" field="payment_price" :min-width="80" />
        <vxe-column title="未入库金额" field="not_inbound_price" :min-width="80" />
        <vxe-column title="货款退款金额" :min-width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_refund_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full" :disabled="form.basic.refund_type !== 4" />
          </template>
        </vxe-column>
        <vxe-column title="申请退运费" :min-width="100">
          <template #default="{ row }">
            <el-input-number v-model="row.apply_tracking_refund_price" :controls="false" :min="0" :step="0.01" :precision="2" class="w-full"
              :disabled="form.basic.refund_type !== 5" />
          </template>
        </vxe-column>
        <vxe-column title="操作" width="80">
          <template #default="{ rowIndex }">
            <el-button link type="danger" @click="form.purchase.splice(rowIndex, 1)">删除</el-button>
          </template>
        </vxe-column>
      </vxe-table>
    </el-form>
    <template #footer>
      <el-button @click="close">取 消</el-button>
      <el-button type="primary" :loading="loadings[2]" @click="create(2)">确 定</el-button>
      <el-button type="primary" :loading="loadings[1]" @click="create(1)">提 交</el-button>
    </template>
  </el-dialog>
</template>

<script setup>
import { nextTick, reactive } from 'vue';
import api from '../api'
import { ElMessage } from 'element-plus'
import { resMessage } from '@/utils/res'
const props = defineProps({
  options: { type: Object, default: () => ({}) },
})
const emit = defineEmits(['close', 'success'])

const load = ref(false)
const visible = ref(false)
let loadings = reactive({})

// 表单处理
const formRef = ref()
const form = ref({})

// 退款类型变化
const refundTypeChange = type => {
  resetRefund()
}
// 重置金额
const resetRefund = () => {
  form.value.purchase.forEach(d => {
    d.apply_refund_price = d.can_refund_price
    d.apply_tracking_refund_price = form.value.basic.refund_type === 4 ? null : d.tracking_price
    d.apply_refund_price = form.value.basic.refund_type === 4 ? d.can_refund_price : ''
  })
}

// 打开弹窗
const open = async (p_ids) => {
  if (!load.value) {
    load.value = true
    await 1
  }
  form.value = {
    basic: {},
    purchase: [],
  }
  loadings = reactive({})
  formRef?.value?.resetFields()

  try {
    const res = await api.selectDetail({ p_ids })
    form.value = res.data
  } catch (error) {
    return
  }
  form.value.basic.refund_type = 4
  form.value.basic.refund_method = 1
  form.value.basic.refund_voucher = []
  resetRefund()
  visible.value = true
}
// 关闭弹窗
const close = () => {
  visible.value = false
}

const handleClose = () => {
  emit('close')
}
const apply_refund_total = computed(() => {
  const { refund_type } = form.value.basic || {};
  const isRefundType4 = refund_type === 4;
  const total = form.value?.purchase?.reduce((acc, item) => {
    const priceKey = isRefundType4 ? "apply_refund_price" : "apply_tracking_refund_price";
    const price = Number(item?.[priceKey] || 0);
    return acc + price;
  }, 0);
  if (form.value.basic) {
    form.value.basic.apply_refund_price = isRefundType4 ? total : 0;
    form.value.basic.apply_refund_tracking_price = isRefundType4 ? 0 : total;
  }
  return total;
});
// 提交
const create = async (is_submit) => {
  const validator = await formRef?.value.validate()
  if (!validator) return
  loadings[is_submit] = true
  form.value.basic.is_submit = is_submit
  api.applyRefund(form.value).then(res => {
    resMessage({
      res,
      success: () => {
        ElMessage.success('操作成功')
        emit('success')
        close()
      }
    })
  }).finally(() => {
    loadings[is_submit] = false
  })
}

defineExpose({ open })
</script>